#!/usr/bin/env python3
"""
API模式配置脚本
快速配置为使用在线API而非本地模型
"""

import os
from pathlib import Path

def setup_api_mode():
    """配置API模式"""
    print("🌐 配置API模式")
    print("=" * 40)
    
    # 配置选项
    print("可用的API选项:")
    print("1. OpenAI API (推荐)")
    print("2. 智谱AI (GLM)")
    print("3. 通义千问 (Qwen)")
    print("4. 文心一言 (ERNIE)")
    print("5. 自定义API")
    
    choice = input("\n请选择API类型 (1-5, 默认1): ").strip()
    if not choice:
        choice = "1"
    
    # API配置
    api_configs = {
        "1": {
            "name": "OpenAI",
            "base_url": "https://api.openai.com/v1",
            "model": "gpt-3.5-turbo",
            "key_name": "OPENAI_API_KEY"
        },
        "2": {
            "name": "智谱AI",
            "base_url": "https://open.bigmodel.cn/api/paas/v4",
            "model": "glm-4",
            "key_name": "ZHIPU_API_KEY"
        },
        "3": {
            "name": "通义千问",
            "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
            "model": "qwen-turbo",
            "key_name": "DASHSCOPE_API_KEY"
        },
        "4": {
            "name": "文心一言",
            "base_url": "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop",
            "model": "ernie-bot-turbo",
            "key_name": "BAIDU_API_KEY"
        },
        "5": {
            "name": "自定义",
            "base_url": input("请输入API基础URL: "),
            "model": input("请输入模型名称: "),
            "key_name": "CUSTOM_API_KEY"
        }
    }
    
    config = api_configs.get(choice, api_configs["1"])
    
    print(f"\n选择了: {config['name']}")
    
    # 获取API密钥
    api_key = input(f"请输入{config['name']} API密钥: ").strip()
    if not api_key:
        print("⚠️ 未输入API密钥，将使用演示模式")
        api_key = "demo_key_please_replace"
    
    # 创建配置文件
    env_file = Path("backend/.env")
    
    # 读取现有配置
    existing_config = {}
    if env_file.exists():
        with open(env_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    existing_config[key.strip()] = value.strip()
    
    # 更新配置
    new_config = {
        **existing_config,
        'LLM_MODE': 'api',
        'API_BASE_URL': config['base_url'],
        'API_MODEL_NAME': config['model'],
        config['key_name']: api_key,
        'MAX_TOKENS': '2048',
        'TEMPERATURE': '0.7',
        'DEBUG': 'true'
    }
    
    # 写入配置文件
    with open(env_file, 'w', encoding='utf-8') as f:
        f.write("# API模式配置\n")
        f.write("# 由setup_api_mode.py自动生成\n\n")
        
        f.write("# === LLM配置 ===\n")
        f.write(f"LLM_MODE={new_config['LLM_MODE']}\n")
        f.write(f"API_BASE_URL={new_config['API_BASE_URL']}\n")
        f.write(f"API_MODEL_NAME={new_config['API_MODEL_NAME']}\n")
        f.write(f"{config['key_name']}={new_config[config['key_name']]}\n")
        f.write(f"MAX_TOKENS={new_config['MAX_TOKENS']}\n")
        f.write(f"TEMPERATURE={new_config['TEMPERATURE']}\n\n")
        
        f.write("# === 其他配置 ===\n")
        for key, value in new_config.items():
            if key not in ['LLM_MODE', 'API_BASE_URL', 'API_MODEL_NAME', config['key_name'], 'MAX_TOKENS', 'TEMPERATURE']:
                f.write(f"{key}={value}\n")
    
    print(f"✅ 配置已保存到 {env_file}")
    
    # 测试配置
    print("\n🧪 测试API配置...")
    test_api_connection(config, api_key)
    
    print("\n🎉 API模式配置完成！")
    print("\n下一步:")
    print("1. 运行 'python start_server.py' 启动服务")
    print("2. 访问前端界面测试功能")
    print("3. 如需修改配置，编辑 backend/.env 文件")

def test_api_connection(config, api_key):
    """测试API连接"""
    try:
        import requests
        
        if config['name'] == "OpenAI":
            headers = {
                'Authorization': f'Bearer {api_key}',
                'Content-Type': 'application/json'
            }
            data = {
                'model': config['model'],
                'messages': [{'role': 'user', 'content': '你好'}],
                'max_tokens': 50
            }
            
            response = requests.post(
                f"{config['base_url']}/chat/completions",
                headers=headers,
                json=data,
                timeout=10
            )
            
            if response.status_code == 200:
                print("✅ API连接测试成功")
            else:
                print(f"⚠️ API测试失败: {response.status_code}")
                print("请检查API密钥和网络连接")
        else:
            print("⚠️ 暂不支持此API的自动测试，请手动验证")
            
    except ImportError:
        print("⚠️ 需要安装requests库: pip install requests")
    except Exception as e:
        print(f"⚠️ API测试出错: {e}")

def main():
    """主函数"""
    print("这个脚本将配置项目使用在线API而非本地模型")
    print("适用于不想安装本地LLM或硬件配置不足的情况\n")
    
    confirm = input("是否继续配置API模式? (y/N): ").strip().lower()
    if confirm in ['y', 'yes', '是']:
        setup_api_mode()
    else:
        print("已取消配置")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n用户取消配置")
    except Exception as e:
        print(f"\n配置过程出现错误: {e}")